<!--
  - Copyright (C) 2024
  - All rights reserved, Designed By www.joolun.com
  - 注意：
  - 本软件为www.joolun.com开发研制，未经购买不得使用
  - 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
  - 一经发现盗用、分享等行为，将追究法律责任，后果自负
-->
<!-- 聊天页面 -->
<template>
	<view>
		<cu-custom :bgColor="globalData.bgColor" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">{{ title }}</block>
		</cu-custom>
		<view>
			<im-connect :fixed="true"></im-connect>
		</view>
		<view>
			<view
				id="chatlist"
				class="cu-chat"
				@click="hideActionModal"
				:style="{
					'padding-bottom': showBottomAction ? '400rpx' : '60rpx'
				}"
			>
				<view class="margin-top message">
					<view class="cu-item" :class="item.sendID == IMuserID ? 'self' : ''" v-for="(item, index) in chatMessageRecord" :key="index" :id="item">
						<view v-if="item.sendID != IMuserID" class="cu-avatar round" :style="{ backgroundImage: 'url(' + item.senderFaceUrl + ')' }"></view>
						<view class="main">
							<!--消息类型 声明文件: MessageType -->
							<!--https://doc.rentsoft.cn/#/js_v2/sdk_integrate/struct?id=%e6%b6%88%e6%81%af%e7%b1%bb%e5%9e%8b      -->
							<view class="content message-bg" :class="item.sendID == IMuserID ? 'bg-white' : ''">
								<view v-if="item.contentType == 110">
									<!-- 自定义的消息类型,可以根据类型分别显示不同的消息,类型可自定义 -->
									<normal-msg :msgBody="item.customElem ? JSON.parse(item.customElem.data) : ''"></normal-msg>
								</view>
								<view v-else>
									<!-- 文本消息 -->
									<view v-if="item.contentType == 101">{{ item.content }}</view>
									<!-- 图片消息 -->
									<view v-else-if="item.contentType == 102"><image-msg :msgBody="item.content ? JSON.parse(item.content) : ''"></image-msg></view>
									<!-- 视频 -->
									<view v-else-if="item.contentType == 104"><video-msg :msgBody="item.content ? JSON.parse(item.content) : ''"></video-msg></view>
								</view>
							</view>
						</view>
						<view v-if="item.sendID == IMuserID" class="cu-avatar round" :style="{ backgroundImage: 'url(' + item.senderFaceUrl + ')' }"></view>
						<view class="date">{{ formatTimeMsg(item.sendTime) }}</view>
					</view>
				</view>
			</view>
			<view class="cu-bar foot input" @tap.stop :style="[{ bottom: InputBottom + 'px' }]">
				<view class="action" @tap="changeActionModal('emoji')">
					<text class="cuIcon-emoji text-grey"></text>
				</view>
				<textarea
					class="solid-bottom padding-tb-sm"
					:adjust-position="false"
					:focus="false"
					maxlength="300"
					cursor-spacing="10"
					@focus="InputFocus"
					@blur="InputBlur"
					:auto-height="true"
					:show-confirm-bar="false"
					v-model="inputMsgText"
				/>
				<view class="action">
					<view class="cuIcon-camera text-grey" @tap="onSendImage()"></view>
				</view>
				<!-- <view class="action" @tap="changeActionModal('action')">
          <text class="cuIcon-add text-grey"></text>
        </view> -->
				<button class="cu-btn bg-green margin-left-sm" style="min-width: 70px" @click="onSendText()">发送</button>
			</view>
			<view v-show="showBottomAction" class="cu-bar foot" style="z-index: 200; overflow-y: auto; height: 400rpx; width: 100%">
				<view v-show="showBottomAction == 'emoji'" class="padding-top-sm">
					<emoji-chat @onClickItem="onChangeEmoji"></emoji-chat>
				</view>
				<view v-show="showBottomAction == 'action'" style="width: 100%">
					<view class="flex align-center bg-gray">
						<view class="padding flex align-center" style="height: 400rpx" @tap="onSendImage()">
							<view class="cu-avatar">
								<view class="cuIcon-camera"></view>
							</view>
						</view>
						<view class="padding flex align-center" style="height: 400rpx" @tap="onSendVideo()">
							<view class="cu-avatar">
								<view class="cuIcon-video"></view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
/**
 * Copyright (C) 2024
 * All rights reserved, Designed By www.joolun.com
 * 注意：
 * 本软件为www.joolun.com开发研制，未经购买不得使用
 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
 */
/**
 * 1.拉取聊天记录
 * 2.如果未联网，显示本地的消息记录
 *
 */

import JimUtil from '@/utils/jim-util'; // IM工具库
import { clearShowNotice } from '@/components/notice/notice-plus-show.js';
import permision from '@/public/app-plus/permission.js';
// 消息处理
import msgUtils from './msg-utils';
// 默认(通用)类型 可显示 订单消息/商品信息消息
import NormalMsg from '@/components/chat-message/msg-type/normal-msg.vue';
// 图片消息
import ImageMsg from '@/components/chat-message/msg-type/image-msg.vue';
// 视频消息
import VideoMsg from '@/components/chat-message/msg-type/video-msg.vue';
// 表情
import EmojiChat from '@/components/chat-message/chat/emoji/emoji.vue';
import imConnect from '@/components/chat-message/im-connect'; //im连接状态

export default {
	components: {
		ImageMsg,
		VideoMsg,
		NormalMsg,
		EmojiChat,
		imConnect
	},
	data() {
		return {
			CustomBar: this.CustomBar,
			// 本地历史消息
			chatRecordLocalSaveKey: 'chat_record_', // key由 当前用户id和客服id组成，保证一对一的数据
			globalData: getApp().globalData,
			chatUserId: null, //客户userId(对方IM的ID)
			title: '消息',
			chatUserinfo: {
				showName: ''
			},
			chatMessageRecord: [],
			inputMsgText: '',
			InputBottom: 0,
			topMsgContent: null, // 顶部消息的内容
			showPage: false, //是否显示页面，用于消息未读数刷新
			sendMsgSuccess: true, // 消息是否发送成功，只有发送成功才能发送下一条
			getMessageOptions: {
				userID: '', //拉取单个用户之间的聊天消息
				groupID: '', //
				startClientMsgID: '', // 起始的消息clientMsgID，第一次拉取为""
				count: 999 //拉取消息的数量
			},
			IMuserID: getApp().globalData.IMdata.IMuserID,
			JIMConnect: false,
			showBottomAction: '' // 底部操作 action emoji
		};
	},
	onShow() {
		this.showPage = true;
		getApp()
			.initJIM()
			.then((res) => {
				this.loadChatRecord();
				this.toBottom();
			})
			.catch((err) => {
				this.loadLocalChatRecord();
			});
		// if(!permision.isIOS){//IOS暂不设置推送
		clearShowNotice(); //清空通知栏消息
		// }
		// 键盘高度监听事件
		// #ifndef H5
		uni.onKeyboardHeightChange((res) => {
			this.InputBottom = res.height;
		});
		// #endif
	},
	onUnload() {
		this.showPage = false;
		uni.$off('JIMLogin');
		uni.$off('JIMDisconnect');
		uni.$off('JIMMsgChange');
		// #ifndef H5
		uni.offKeyboardHeightChange((res) => {
			this.InputBottom = 0;
		});
		// #endif
		//当前聊天页面的用户ID,用来判断是否需要显示通知栏消息
		getApp().globalData.chatUserId = null;
	},
	onHide() {
		this.showPage = false;
	},
	onLoad(options) {
		this.chatUserId = options.chatUserId; //userId（聊天对象ID）
		// 当前聊天对象 当前聊天页面的用户ID,用来判断是否需要显示通知栏消息
		getApp().globalData.chatUserId = this.chatUserId;
		if (options.showName) {
			this.title = options.showName;
		}
		//当前登录人
		this.IMuserID = JimUtil.GetIMuserID();
		this.showPage = true;
		this.getMessageOptions.userID = this.chatUserId;
		this.chatRecordLocalSaveKey = 'chat_record_' + this.IMuserID + this.chatUserId;

		// 连接断开监听
		uni.$on('JIMDisconnect', (data) => {
			this.loadLocalChatRecord();
		});
		// 登录监听
		uni.$on('JIMLogin', (data) => {
			this.loadChatRecord();
		});
		// 收到消息监听
		uni.$on('JIMMsgChange', (data) => {
			if (this.showPage) {
				this.loadChatRecord();
			}
		});
	},
	methods: {
		/**
		 * 发送消息成功处理
		 */
		sendMsgSuccessHandle(data) {
			this.chatMessageRecord.push(JSON.parse(data));
			this.inputMsgText = '';
			this.hideActionModal();
			this.toBottom();
			JimUtil.saveIMMsg(this.chatMessageRecord, this.getMessageOptions.userID);
			this.topMsgContent = null;
			this.sendMsgSuccess = true;
		},
		//获取聊天记录 https://doc.rentsoft.cn/#/js_v2/sdk_integrate/message?id=gethistorymessagelist
		loadChatRecord() {
			if (!this.showPage) return;
			let JIM = getApp().globalData.JIM;
			// 下方初始化聊天记录
			// 拉取本地的消息数据并保存
			JIM.getHistoryMessageList(this.getMessageOptions)
				.then((res) => {
					const data = JSON.parse(res.data) || [];
					JimUtil.saveIMMsg(data);
					this.chatMessageRecord = data;
					this.toBottom();
				})
				.catch((err) => {
					//读取本地消息
					this.loadLocalChatRecord();
				});
			// 设置消息已读，更新会话未读数数据
			msgUtils.markMsgRead(JIM, this.chatUserId);
		},
		// 读取服务器聊天记录失败时读取本地缓存聊天记录
		loadLocalChatRecord() {
			if (!this.showPage) return;
			// 取出保存的聊天数据
			let localMsgStr = uni.getStorageSync(this.chatRecordLocalSaveKey); // 本地消息
			const data = localMsgStr ? JSON.parse(localMsgStr) : [];
			this.chatMessageRecord = data;
			this.toBottom();
		},
		// 滑动到页面最下面
		toBottom() {
			let that = this;
			setTimeout(function () {
				if (that.showPage) {
					uni.pageScrollTo({
						scrollTop: 9999999
					});
				}
			}, 1000);
		},
		// 编辑框事件
		InputFocus(e) {
			// APP底部有虚拟导航栏，需要动态计算一下高度
			let sysInfo = uni.getSystemInfoSync();
			let heightDiff = sysInfo.screenHeight - sysInfo.windowHeight;
			let diff = e.detail.height - heightDiff;
			this.InputBottom = diff > 0 ? diff : 0;
			this.showBottomAction = '';
		},
		InputBlur(e) {
			this.hideActionModal();
		},
		// 添加emoji表情到输入框
		onChangeEmoji(value) {
			this.inputMsgText += value;
		},
		formatTimeMsg(time) {
			return JimUtil.parseTimeMsg(time);
		},

		// 显示隐藏操作按钮
		changeActionModal(type) {
			if (this.showBottomAction == type) {
				this.hideActionModal();
				return;
			}
			this.InputBottom = 0;
			this.showBottomAction = '';
			let sysInfo = uni.getSystemInfoSync();
			// 延迟一下等待键盘关闭
			setTimeout(() => {
				// #ifdef H5
				this.InputBottom = 215;
				// #endif
				// #ifndef H5
				// 注意: 微信小程序模拟器的高度显示有问题,这里处理一下
				if (sysInfo.platform == 'devtools') {
					this.InputBottom = 190;
				} else {
					this.InputBottom = 200;
				}
				// #endif
				this.showBottomAction = type;
			}, 100);
		},
		//隐藏操作按钮
		hideActionModal() {
			this.InputBottom = 0;
			this.showBottomAction = '';
		},
		// 文本消息
		onSendText() {
			var that = this;
			var inputMsgText = that.inputMsgText;
			if (!inputMsgText || inputMsgText == '' || inputMsgText.trim().length == 0) {
				//无内容直接跳出
				return;
			}
			if (!this.sendMsgSuccess) {
				//消息正在发送中
				uni.showToast({
					title: '正在发送中',
					icon: 'none'
				});
				return;
			}
			this.sendMsgSuccess = false;
			let JIM = getApp().globalData.JIM;
			msgUtils
				.sendMsgText(JIM, this.getMessageOptions.userID, inputMsgText)
				.then((data) => {
					this.sendMsgSuccessHandle(data);
				})
				.catch(() => {});
		},
		// 发送图片消息
		onSendImage() {
			let JIM = getApp().globalData.JIM;
			uni.chooseImage({
				count: 1, //默认9
				sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				success: (chooseRes) => {
					msgUtils
						.sendMsgImage(JIM, this.getMessageOptions.userID, chooseRes.tempFiles[0])
						.then((data) => {
							this.sendMsgSuccessHandle(data);
						})
						.catch(() => {});
				}
			});
		},
		// 发送视频消息
		onSendVideo() {
			let JIM = getApp().globalData.JIM;
			uni.chooseVideo({
				compressed: false, //是否压缩视频
				success: (file) => {
					msgUtils
						.sendMsgVideo(JIM, this.getMessageOptions.userID, file)
						.then((data) => {
							this.sendMsgSuccessHandle(data);
						})
						.catch(() => {});
				}
			});
		}
	}
};
</script>
<style>
.goods-bg {
	width: 94%;
	border-radius: 10rpx;
	margin: auto;
}

.image-box {
	margin: auto;
	width: 180rpx;
	height: 180rpx;
}

.message {
	margin-bottom: 100rpx !important;
	padding-bottom: 100rpx;
}

.message-bg {
	border-radius: 10rpx !important;
	word-break: break-all;
	word-wrap: break-word;
}
</style>